﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Activation;
using System.Web.Routing;
using System.Reflection;

using System.Xml.Linq;

namespace WcfServicePush.Service  
{
    public class WCFSwichUtility
    {
        private static WebServiceHostFactory webservicefactory;

        static WCFSwichUtility()
        { 
            webservicefactory = new WebServiceHostFactory();
        }
        /// <summary>
        /// 设置服务路由
        /// </summary>
        public static void WCFRESTSetServiceHosts()
        {
            XElement root = XElement.Load(HttpContext.Current.Server.MapPath("Service/WCFRESTService.xml"));
            foreach (XElement xel in root.Elements("Service"))
            {
                AddRoute(xel);
            }
        }
        
        /// <summary>
        /// 根据条件决定路由的Host类型
        /// </summary>
        /// <param name="xel">是否对该服务启用路由</param> 
        private static void AddRoute(XElement xel)
        {
            try
            { 
                string servicename = xel.Attribute("name").Value;
                string serviceclass = xel.Attribute("Class").Value;
                Type t = Type.GetType(serviceclass);

                RouteTable.Routes.Add(new ServiceRoute(servicename, webservicefactory, t));
            }
            catch (Exception exception)
            {
                ExceptionManage.ExceptionHandle(exception);
            }
        }
    } 
}